const DUATION = 1000;
const DISTANCE = 100;

const map = new WeakMap();

const observe = new IntersectionObserver((entries, observe) => {
  entries.forEach((entry) => {
    if (entry.isIntersecting) {
      const animation = map.get(entry.target);
      animation && animation.play();
      // observe.unobserve(entry.target);
    }
  });
});

const isBlowViewport = (el) => {
  return el.getBoundingClientRect().top - window.innerHeight > 0;
};
// 滚动平滑动画
export const scrollMooth = {
  mounted(el, binding) {
    // 指令逻辑
    // if (!isBlowViewport(el)) {
    //   return;
    // }
    const animation = el.animate(
      [
        { transform: `translateY(${DISTANCE}px)`, opacity: 0.2 },
        {
          transform: `translateY(0px)`,
          opacity: 1,
        },
      ],
      {
        duration: DUATION,
        easing: "ease-out",
        fill: "forwards",
      }
    );
    animation.pause();
    map.set(el, animation);
    observe.observe(el);
  },
  unmounted(el) {
    observe.unobserve(el);
  },
};
